package com.navi168.fwq21.monitoring;

import java.nio.MappedByteBuffer;
import java.util.ArrayList;
import java.util.Random;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import com.amap.a.a;
import com.amap.mapapi.core.GeoPoint;
import com.amap.mapapi.map.MapActivity;
import com.amap.mapapi.map.MapController;
import com.amap.mapapi.map.MapView;
import com.amap.mapapi.map.Overlay;
import com.navi168.fwq21.R;
import com.navi168.fwq21.monitoring.mod.Track;

import android.R.integer;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Paint.Style;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.ToggleButton;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class TrackShow extends MapActivity {
	private Button cancebutton;
	private ToggleButton isshowButton;
	private MapView mapView;
	private Context context;
	private LinearLayout sdtLayout;
	private static final String SPF = "NAVI168";
	private String TAG = "mylog";
	private String title = "speed chart";
	private boolean gps_flag;// 可否定位开关
	private GeoPoint point;
	private MapController mMapController;
	private ArrayList<GeoPoint> geoPoints = new ArrayList<GeoPoint>();
	private ArrayList<Point> points = new ArrayList<Point>();

	ArrayList<Track> tracks = new ArrayList<Track>();
	private Button start;
	private Button pause;
	private Button stop;
	private SeekBar contr;
	private int progress;

	private GeoPoint geoPoint;

	private XYSeries series;
	private XYMultipleSeriesDataset mDataset;
	private GraphicalView chart;
	private XYMultipleSeriesRenderer renderer;
	private int addX = -1, addY; 
	int[] xv = new int[30];  
    int[] yv = new int[30];

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gjhfshowmap);
		context = getApplicationContext();
		findviews();
		setlisters();

		SharedPreferences settings = getSharedPreferences(SPF,
				MODE_WORLD_READABLE);
		gps_flag = settings.getBoolean("auto_loc", true);
		point = new GeoPoint(
				settings.getInt("city_lat", (int) (31.18334 * 1E6)),
				settings.getInt("city_long", (int) (121.43348 * 1E6)));
		mapView.setBuiltInZoomControls(true);
		mMapController = mapView.getController();
		mMapController.setCenter(point); // 设置地图中心点
		mMapController.setZoom(13);

		for (int a = 0; a < 10; a++) {
			float b = (float) (0.1 * a);
			Track track = new Track();
			track.setDate("2012-12-12 12:12");
			track.setLat((int) ((31.18334 + b) * 1E6));
			track.setLon((int) ((121.43348 + b) * 1E6));
			track.setMileage(123 + a);
			track.setSpeed(50);
			tracks.add(track);
		}

		contr.setMax(tracks.size());// 设置seekbar的最大值
		mapView.getOverlays().add(new MyOverlay());
		
		
		init_speed();
		

	}

	private void init_speed() {
		// TODO 速度图相关
		series = new XYSeries(title);
		mDataset = new XYMultipleSeriesDataset();
		mDataset.addSeries(series);
		int color = Color.GREEN;  
        PointStyle style = PointStyle.SQUARE;
        renderer = buildRenderer(color, style, true);
        setChartSettings(renderer, "X", "Y", 0, 30, 0, 120, Color.WHITE, Color.WHITE);
        chart = ChartFactory.getLineChartView(context, mDataset, renderer);
        sdtLayout.addView(chart, new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
        sdtLayout.setVisibility(View.GONE);
	}

	private void setlisters() {
		cancebutton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				TrackShow.this.finish();

			}
		});

		start.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.i(TAG, "开始按钮");
				// handler.post(start_thread);
				handler.post(updateseek);

			}
		});

		pause.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				handler.removeCallbacks(updateseek);

			}

		});

		stop.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				contr.setProgress(0);
				handler.removeCallbacks(updateseek);

			}
		});

		contr.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub

			}
		});
		
		isshowButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					sdtLayout.setVisibility(View.VISIBLE);
				}else {
					sdtLayout.setVisibility(View.GONE);
				}
				
			}
		});
	}

	private void findviews() {

		mapView = (MapView) findViewById(R.id.poisearch_MapView);
		cancebutton = (Button) findViewById(R.id.cance);
		start = (Button) findViewById(R.id.start);
		pause = (Button) findViewById(R.id.pause);
		stop = (Button) findViewById(R.id.stop);
		contr = (SeekBar) findViewById(R.id.seekbarcontr);
		sdtLayout = (LinearLayout) findViewById(R.id.sdtlayout);
		isshowButton = (ToggleButton) findViewById(R.id.isshow);

	}

	private ArrayList<Point> getPoints(ArrayList<Track> tracks) {
		ArrayList<Point> points = new ArrayList<Point>();
		ArrayList<GeoPoint> geoPoints = new ArrayList<GeoPoint>();
		for (Track track : tracks) {
			GeoPoint gPoint = new GeoPoint(track.getLat(), track.getLon());
			geoPoints.add(gPoint);
		}

		for (GeoPoint gPoint : geoPoints) {
			Point point = new Point();
			mapView.getProjection().toPixels(gPoint, point);
			points.add(point);
		}

		return points;

	}

	private ArrayList<GeoPoint> getGeoPoints(ArrayList<Track> tracks) {

		ArrayList<GeoPoint> geoPoints = new ArrayList<GeoPoint>();
		for (Track track : tracks) {
			GeoPoint gPoint = new GeoPoint(track.getLat(), track.getLon());
			geoPoints.add(gPoint);
		}

		return geoPoints;

	}

	public class MyOverlay extends Overlay {

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			// TODO Auto-generated method stub
			super.draw(canvas, mapView, shadow);

			// 经度转像素

			float dddd = mapView.getProjection().metersToEquatorPixels(6);
			// ---add the marker---

			Paint paint = new Paint();
			paint.setColor(Color.BLUE);
			paint.setDither(true);
			paint.setStyle(Paint.Style.STROKE);
			paint.setStrokeJoin(Paint.Join.ROUND);
			paint.setStrokeCap(Paint.Cap.ROUND);
			paint.setStrokeWidth(4 * dddd);

			Path path = new Path();

			points = getPoints(tracks);

			for (int i = 0; i < points.size(); i++) {
				if (i == 0) {
					path.moveTo(points.get(i).x, points.get(i).y);
				} else {
					path.lineTo(points.get(i).x, points.get(i).y);
				}
			}

			canvas.drawPath(path, paint);
		}

		@Override
		public boolean onTap(GeoPoint arg0, MapView arg1) {
			// TODO Auto-generated method stub
			return super.onTap(arg0, arg1);
		}

	}

	public class Thumbtack extends Overlay {
		private View popUpView;
		private LayoutInflater inflater;
		private Context context;
		private GeoPoint gPoint;

		public Thumbtack(Context context, GeoPoint gPoint) {
			this.context = context;
			inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			this.gPoint = gPoint;
		}

		@Override
		public void draw(Canvas canvas, MapView arg1, boolean arg2) {

			super.draw(canvas, arg1, arg2);
			Point screenPts = new Point();
			mapView.getProjection().toPixels(gPoint, screenPts);
			Bitmap bmp = BitmapFactory.decodeResource(getResources(),
					R.drawable.da_marker_red);
			canvas.drawBitmap(bmp, screenPts.x - 18, screenPts.y - 64, null);

		}

		@Override
		public boolean onTap(GeoPoint geo, final MapView view) {
			// TODO Auto-generated method stub
			if (popUpView != null) {
				view.removeView(popUpView);
			}
			popUpView = inflater.inflate(R.layout.popup2, null);
			TextView textView = (TextView) popUpView.findViewById(R.id.PoiName);
			TextView adressTextView = (TextView) popUpView
					.findViewById(R.id.PoiAddress);
			textView.setText("设备状态：离线\nNavi168状态：运行");
			adressTextView.setText("时间2012-02-02 00：00：00\n速度：15km");
			MapView.LayoutParams lp;
			lp = new MapView.LayoutParams(MapView.LayoutParams.WRAP_CONTENT,
					MapView.LayoutParams.WRAP_CONTENT, gPoint, 15, -50,
					MapView.LayoutParams.BOTTOM_CENTER);
			view.addView(popUpView, lp);
			popUpView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					view.removeView(popUpView);
				}
			});
			return super.onTap(geo, view);
		}

	}

	private Handler handler = new Handler(

	) {

		@Override
		public void handleMessage(Message msg) {
			Log.i(TAG, "msg what is " + msg.what);
			ArrayList<GeoPoint> gps = getGeoPoints(tracks);
			int lat = gps.get(msg.what).getLatitudeE6();
			int lon = gps.get(msg.what).getLongitudeE6();
			Log.i(TAG, lat + "-" + lon);

			GeoPoint gp = new GeoPoint(lat, lon);

			/*
			 * if (mapView.getOverlays().size() > 1) {
			 * mapView.getOverlays().remove(1); Log.i(TAG,
			 * mapView.getOverlays().size() + " mapView.getOverlays().size");
			 * mapView.getOverlays().add(new Thumbtack(context, gp)); } else {
			 * Log.i(TAG, mapView.getOverlays().size() +
			 * " mapView.getOverlays().size"); mapView.getOverlays().add(new
			 * Thumbtack(context, gp)); }
			 */
			if (mapView.getOverlays().size() > 1) {
				mapView.getOverlays().remove(1);
			}
			mapView.getOverlays().add(new Thumbtack(context, gp));
			mapView.invalidate();
			updateChart(msg.what);
			chart.invalidate();

		}

	};

	Thread start_thread = new Thread(new Runnable() {

		@Override
		public void run() {

			for (int i = 0; i < tracks.size(); i++) {
				Log.i(TAG, "开始画轨迹！ " + i);
				// geoPoint = new GeoPoint(tracks.get(i).getLat(), tracks.get(i)
				// .getLon());
				// progress = i + 1;
				/*
				 * if (i == 0) { mapView.getOverlays().add(new
				 * Thumbtack(context, geoPoint)); contr.setProgress(i + 1);
				 * Log.i(TAG, "第一个图 "); } else { contr.setProgress(i + 1); // if
				 * (mapView.getOverlays().size() > 2) { //
				 * mapView.getOverlays().remove(1); // } Log.i(TAG, "之后的图 ");
				 * mapView.getOverlays().add(new Thumbtack(context, geoPoint));
				 * }
				 */

				handler.sendEmptyMessage(1);
				try {
					start_thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			contr.setProgress(0);
			handler.sendEmptyMessage(2);

		}

	});

	Thread updateseek = new Thread(new Runnable() {

		@Override
		public void run() {

			progress = contr.getProgress() + 1;
			contr.setProgress(progress);
			Log.i(TAG, "tracks.size(): " + tracks.size() + "progress: "
					+ progress);
			if (progress-1 < tracks.size()) {
				handler.sendEmptyMessage(progress-1);

				handler.postDelayed(updateseek, 1000);
			} else {
				contr.setProgress(0);
				handler.removeCallbacks(updateseek);
			}

		}
	});
	
	
	
	protected XYMultipleSeriesRenderer buildRenderer(int color, PointStyle style, boolean fill) {  
        XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();  
          
        //设置图表中曲线本身的样式，包括颜色、点的大小以及线的粗细等  
        XYSeriesRenderer r = new XYSeriesRenderer();  
        r.setColor(color);  
        r.setPointStyle(style);  
        r.setFillPoints(fill);  
        r.setLineWidth(2);  
        renderer.addSeriesRenderer(r);  
          
        return renderer;  
    }  
      
    protected void setChartSettings(XYMultipleSeriesRenderer renderer, String xTitle, String yTitle,  
                                    double xMin, double xMax, double yMin, double yMax, int axesColor, int labelsColor) {  
        //有关对图表的渲染可参看api文档  
        renderer.setChartTitle(title);
        renderer.setMargins(new int[] { 20, 30, 15, 20 });
        renderer.setXTitle(xTitle);  
        renderer.setYTitle(yTitle);  
        renderer.setXAxisMin(xMin);
        renderer.setXLabelsColor(Color.BLACK);
        renderer.setXAxisMax(xMax);  
        renderer.setYAxisMin(yMin);  
        renderer.setYAxisMax(yMax);  
        renderer.setAxesColor(axesColor);  
        renderer.setLabelsColor(labelsColor);  
        renderer.setShowGrid(true);  
        renderer.setGridColor(Color.YELLOW);  
        renderer.setXLabels(15);  
        renderer.setYLabels(10);  
        renderer.setXTitle("");  
        renderer.setYTitle("KM/h");  
        renderer.setYLabelsAlign(Align.RIGHT);  
        renderer.setPointSize((float) 2);  
        renderer.setShowLegend(false);  
    }  
    
    
    private void updateChart(int postion) {
    	
    	Log.i(TAG, postion+"次执行");
    	 Random random = new Random();
    	int speed = tracks.get(postion).getSpeed();
    	addX = 0;
    	addY = speed*random.nextInt(3);
    	Log.i(TAG, addY+"addY");
    	
        
        //设置好下一个需要增加的节点  
//        addX = 0;  
//        addY = (int)(Math.random() * 90);  
          
        //移除数据集中旧的点集  
        mDataset.removeSeries(series);  
          
        //判断当前点集中到底有多少点，因为屏幕总共只能容纳100个，所以当点数超过100时，长度永远是100  
        int length = series.getItemCount();
        if (length > 30) {  
            length = 30;  
        }  
          
        //将旧的点集中x和y的数值取出来放入backup中，并且将x的值加1，造成曲线向右平移的效果  
        for (int i = 0; i < length; i++) {  
            xv[i] = (int) series.getX(i) + 5;  
            yv[i] = (int) series.getY(i);  
        }  
          
        //点集先清空，为了做成新的点集而准备  
        series.clear();  
          
        //将新产生的点首先加入到点集中，然后在循环体中将坐标变换后的一系列点都重新加入到点集中  
        //这里可以试验一下把顺序颠倒过来是什么效果，即先运行循环体，再添加新产生的点  
        series.add(addX, addY);  
        for (int k = 0; k < length; k++) {
            series.add(xv[k], yv[k]);  
        }  
          
        //在数据集中添加新的点集  
        mDataset.addSeries(series);
          
        //视图更新，没有这一步，曲线不会呈现动态  
        //如果在非UI主线程中，需要调用postInvalidate()，具体参考api  
          
    }  

}
